package com.zjm.principle.ocp;

import java.util.ArrayList;
import java.util.List;

/**
 * 开闭原则
 */
public class OpenClosed {
    public static void main(String[] args) {
        List<Shape> shapes = new ArrayList<>();
        shapes.add(new Rectangle(5, 4));
        shapes.add(new Circle(3));

        AreaCalculator calculator = new AreaCalculator();
        System.out.println("总面积：" + calculator.calculateTotalArea(shapes));
    }
}

// 1. 定义抽象接口或基类
interface Shape {
    double area();
}

// 2. 实现具体图形类
class Rectangle implements Shape {
    private final double width;
    private final double height;

    public Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }

    public double getWidth() {
        return width;
    }

    public double getHeight() {
        return height;
    }

    @Override
    public double area() {
        return width * height;
    }
}

class Circle implements Shape {
    private final double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    public double getRadius() {
        return radius;
    }

    @Override
    public double area() {
        return Math.PI * radius * radius;
    }
}

// 图形计算器（不需要修改，即可支持新图形）
class AreaCalculator {
    public double calculateTotalArea(List<Shape> shapes) {
        return shapes.stream()
            .mapToDouble(Shape::area)
            .sum();
    }
}

// 违法开闭原则
class AreaCalculator2 {
    public double calculateTotalArea(List<Object> shapes) {
        double total = 0;
        for (Object shape : shapes) {
            if (shape instanceof Rectangle) {
                total += ((Rectangle) shape).getWidth() * ((Rectangle) shape).getHeight();
            } else if (shape instanceof Circle) {
                total += Math.PI * ((Circle) shape).getRadius() * ((Circle) shape).getRadius();
            }
        }
        return total;
    }
}
